<?php

namespace Yjius\aibigmodel\chatgpt;

use Yjius\aibigmodel\AIBigModelBuilderInterface;
use Yjius\common\LoggerHelper;

class ChatgptMetaWa implements AIBigModelBuilderInterface
{
    //实例化代码
    static private $instance;

    private function __construct($params)
    {
        $this->chatUrl = $params['chat_url'] ?? "http://198.11.179.183:6097";
        $this->chatModel = $params['chat_model'] ?? "";//调用GPT-4o
        $this->apiKey = $params['api_key'] ?? "";
        if (empty($this->apiKey)) {
            throw new \Exception("Chatgpt:api_key不能为空");
        }
        $this->saveLog = $params['save_log'] ?? false;
        if ($this->saveLog) {
            $this->loggerInstance = LoggerHelper::init();
        }
    }

    private function __clone()
    {
    }

    //单例模式
    static public function getInstance($params)
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    function chatOnce(array $paramsArray, array $customerParams)
    {
        //调用元哇的接口，仅仅支持问答操作
        $data = [
            'msg' => "hello！",
        ];
        //统一结构转换
        if (!empty($paramsArray["messages"])) {
            foreach ($paramsArray["messages"] as $value) {
                if ($value["role"] == 'user') {
                    $question = $value['content'] ?? "";
                    break;
                }
            }
        }
        if (!empty($question)) {
            $data['msg'] = "$question";
        }
        $res = $this->curlRequest($data);
        if ($this->saveLog) {
            //问题结果日志记录
            $this->loggerInstance->write("chatgpt_" . $this->apiKey . ".log", json_encode($data, JSON_UNESCAPED_UNICODE));
            $this->loggerInstance->write("chatgpt_" . $this->apiKey . ".log", $res);
        }
        return $res;
    }

    function chatOnceDealResult(string $paramsStr, array $customerParams)
    {
        try {
            // 将JSON字符串转换为关联数组
            $dataArr = json_decode($paramsStr, true);

            // 提取并返回聊天内容
            return $dataArr['data']['answer'] ?? '';
        } catch (\Exception $e) {
            // 直接返回null，不记录错误信息
            return null;
        }
    }

    private function curlRequest($data = [])
    {
        // 设置请求头
        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ];

        $ch = curl_init(); // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $this->chatUrl); // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_TIMEOUT, 1200);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLINFO_HEADER_OUT, true); /* 请求头 */
        curl_setopt($ch, CURLOPT_HEADER, false); /* 返回头 */
        curl_setopt($ch, CURLOPT_POST, 1); // 发送一个常规的Post请求

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

        // 执行cURL会话
        $response = curl_exec($ch);

        // 检查是否有错误发生
        $errno = curl_errno($ch);       //curl错误码
        $error = curl_error($ch);       //curl错误信息

        if ($errno) {         //curl异常
            $curlError = json_encode(['curl_errno' => $errno, 'curl_error' => $error], JSON_UNESCAPED_UNICODE);
            throw new \Exception("curl异常：" . $curlError);
        }
        // 关闭cURL资源
        curl_close($ch);
        // 关闭cURL资源
        return $response;
    }

}